package com.hanhai.zrb.mobile.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hanhai.common.cache.Cache;
import com.hanhai.common.util.MD5Util;
import com.hanhai.zrb.api.biz.result.UserCenterResult;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.SMSCodeService;
import com.hanhai.zrb.api.biz.service.UserInfoService;
import com.hanhai.zrb.api.biz.service.UserRegisterCheckService;
import com.hanhai.zrb.api.biz.service.UserRegisterService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.biz.service.UserStatisticDetailService;
import com.hanhai.zrb.mobile.result.BaseApiResult;
import com.hanhai.zrb.mobile.service.LoginUserService;
import com.hanhai.zrb.mobile.util.FrontLoginUtil;
import com.hanhai.zrb.model.common.BaseUser;
import com.hanhai.zrb.model.common.ValidateCodeSend.BizTypeEnum;
import com.hanhai.zrb.model.common.ValidateCodeSend.SendSMSTypeEnum;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.UserInfo;
import com.hanhai.zrb.model.user.UserStatisticDetail;
import com.hanhai.zrb.model.user.enums.GenderParam;
import com.hanhai.zrb.model.user.enums.UserInfoName;
import com.hanhai.zrb.model.user.vo.UserInfoVO;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
@RequestMapping("/user")
@RestController
public class UserApiController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private CityInfoService cityInfoService;
	@Resource
	private LoginUserService loginUserService;
	@Resource
	private UserRegisterCheckService userRegisterCheckService;
	
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private Cache loginCache;
	@Resource
	private UserStatisticDetailService userStatisticDetailService;
	@Resource
	private  UserRegisterService userRegisterService;
	@Resource
	private UserService userService;
	@Resource
	private SMSCodeService sMSCodeService;
	/*@Value("#{configProperties['zhaorongbao.img.url']}")
	private String img_url;*/
	
	private static String regpw = "^[^\\s]{6,16}$";
	private static String regEmail = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$";
	private static String regIdCard = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";

	
	private static String regMobile = "^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$";

	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "咨询/关注/分享",  response = Boolean.class, notes = "咨询/关注/分享")
	@RequestMapping("/interest/doAdd")
	public BaseApiResult collectionAdd(
			@ApiParam(required = true, name = "id", value = "id")
			@RequestParam(value = "id", required = true)Long id,
			@ApiParam(required = true, name = "type", value = "类型")
			@RequestParam(value = "type", required = true)Integer type){
		BaseUser user = FrontLoginUtil.getCurrentUser();
		BaseApiResult result = new BaseApiResult();
		UserStatisticDetail userStatisticDetail = new UserStatisticDetail();
		userStatisticDetail.setDestId(id);
		userStatisticDetail.setType(type);
		userStatisticDetail.setUserId(user.getUid());
		boolean bool = userStatisticDetailService.doCollection(userStatisticDetail);
		result.setData(bool);
		return result;
	}
	
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "取消咨询/关注/分享",  response = Boolean.class, notes = "取消咨询/关注/分享")
	@RequestMapping("/interest/doCancel")
	public BaseApiResult collectionCancel(
			@ApiParam(required = true, name = "id", value = "id")
			@RequestParam(value = "id", required = true)Long id,
			@ApiParam(required = true, name = "type", value = "类型")
	        @RequestParam(value = "type", required = true)Integer type){
		BaseUser user = FrontLoginUtil.getCurrentUser();
		BaseApiResult result = new BaseApiResult();
		UserStatisticDetail userStatisticDetail = new UserStatisticDetail();
		userStatisticDetail.setDestId(id);
		userStatisticDetail.setType(type);
		userStatisticDetail.setUserId(user.getUid());
		boolean bool = userStatisticDetailService.doCancelCollection(userStatisticDetail);
		result.setData(bool);
		return result;
	}
	
	
	@RequestMapping("/doUserInfo")
	public BaseApiResult doUserInfo(HttpServletRequest request, HttpServletResponse response) {
		BaseApiResult result =new BaseApiResult();
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();

		User user = userService.findById(baseUser.getUid());
		try {
			Map<String,Object> data = buildApiForUserInfo(user);
			result.setData(data);
			result.setRes(1);
		} catch (Exception e) {
			logger.error("",e);
			result.setRes(0);
		}

		return result;
	}
	
	

	private Map<String,Object> buildApiForUserInfo(User user){
		Map<String,Object> data = new HashMap<String,Object>();
		data.put("uid", user.getUid());
		data.put("uname", user.getUname());
		//职务
		List<UserInfoName> queryNameList = new ArrayList<UserInfoName>();
		queryNameList.add(UserInfoName.POSITION);
		UserInfoVO userInfoVo = userInfoService.findByNameEnums(Long.toString(user.getUid()), queryNameList);
		Map<String, String> infoMap = userInfoVo.getInfoMap();
		String position = infoMap.get("POSITION");
		data.put("position", position);
		//行业
		data.put("industry", user.getIndustry());
		//行业id
		data.put("industryId", user.getIndustryId());
		
		data.put("auth", user.getStatus()==12?true:false);
		data.put("org", user.getOrg()==null?"":user.getOrg());
		data.put("orgId", user.getOrgId()==null?"":user.getOrgId().toString());
		data.put("userType", user.getUid().toString().startsWith("200")?"2":"1");
		data.put("userTypeName", user.getUid().toString().startsWith("200")?"政府":"企业");
		data.put("uEmail", user.getUemail()==null?"":user.getUemail());
		data.put("uMobile", user.getUmobile());
		data.put("realname", user.getRealname()==null?"":user.getRealname());
		data.put("status", user.getStatus());
		data.put("statusName", user.getStatus()==12?"已认证":"未认证"); //12:已认证    11:未认证
		data.put("idCard", user.getIdcard()==null?"":user.getIdcard());
		String imgpath = user.getAvatar();
		if(StringUtils.isNotBlank(imgpath)){
			imgpath = imgpath;
		}else{
			imgpath="";
		}
		
		data.put("avatar",imgpath);
		
		List<UserInfoName> queryEmunList  = new ArrayList<UserInfoName>();
		queryEmunList.add(UserInfoName.GENDER);
		queryEmunList.add(UserInfoName.INFO);
		queryEmunList.add(UserInfoName.LOCATION);
		queryEmunList.add(UserInfoName.BIRTHDATE);
		queryEmunList.add(UserInfoName.IDCARD_PROVINCE);
		queryEmunList.add(UserInfoName.IDCARD_CITY);
		Map<String, String> map = findByNameEnumsForMap(user.getUid().toString(),queryEmunList);
		
		  for (Map.Entry<String, String> entry : map.entrySet()) {
			  data.put(entry.getKey(), entry.getValue());
		  }
		return data;
	}
	
	private Map<String, String>  findByNameEnumsForMap(String id,List<UserInfoName> queryEmunList){
		Map<String, String> mapRet = new HashMap<String, String>();
		mapRet.put("GENDER",""); 
		mapRet.put("GENDERNAME",""); 
		mapRet.put("LOCATION",""); 
		mapRet.put("LOCATIONNAME",""); 
		mapRet.put("BIRTHDATE",""); 
		mapRet.put("IDCARD_PROVINCE",""); 
		mapRet.put("IDCARD_CITY","");
		mapRet.put("INFO",""); 
		UserInfoVO userInfoVO = new UserInfoVO();
		userInfoVO = userInfoService.findByNameEnums(id, queryEmunList);
			  Map<String, String> map = userInfoVO.getInfoMap();
			  for (Map.Entry<String, String> entry : map.entrySet()) {
				  if("GENDER".equals(entry.getKey())){//性别:0-未知(UserAuthName),1-男(UserAuthName),2-女
						for(GenderParam status :GenderParam.values()){
							if((status.getCode().toString()).equals(entry.getValue())){
								mapRet.put("GENDERNAME",status.getValue());
							}
						}
					  mapRet.put("GENDER",entry.getValue()); 
				  }else if("LOCATION".equals(entry.getKey())){
					  //获取当前地区的中文字符和编码
					  try {
						  CityInfo cityInfo = cityInfoService.selectByPostcode(entry.getValue());
						  //District  district = districtService.selectByCode(entry.getValue());
						  //District  province = districtService.selectByCode(entry.getValue().substring(0, 2)+"0000");
						  CityInfo  province = cityInfoService.selectByPostcode(entry.getValue().substring(0, 2)+"0000");
						  if(null!=cityInfo){
							  mapRet.put("LOCATIONNAME",province.getCityName()+" "+cityInfo.getCityName());
						  }
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
					  mapRet.put("LOCATION",entry.getValue());  
				  }else{
					  mapRet.put(entry.getKey(),entry.getValue());  
				  }
				  				  
			  }

		return mapRet;
	}
	
	
	/** 
	 * @Title: changePWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param request
	 * @param @param response
	 * @param @param mobile
	 * @param @param passWord
	 * @param @param smsCode
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "保存修改密码",  response = BaseApiResult.class, notes = "修改密码")
	@RequestMapping(value="/changePWord")
	public BaseApiResult changePWord(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "oldpassWord", value = "旧密码")@RequestParam(value = "passWord", required = true)String passWord,
			@ApiParam(required = true, name = "newpassWord", value = "新密码")@RequestParam(value = "newpassWord", required = true)String newpassWord)
       {
		BaseApiResult result = new BaseApiResult();
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();
			
		
		String mobile = baseUser.getMobile();
		if( StringUtils.isNotBlank(mobile)){
            //判断旧密码是否跟数据库保存密码一致
			String checkPwd = MD5Util.sha1(passWord);
			boolean passwordRight = StringUtils
					.equals(baseUser.getPassword(), checkPwd);
			if (passwordRight) {
				if( newpassWord.trim().matches(regpw)){
					
					try {
						userService.updatePwdByMobile( mobile, newpassWord);
						logger.info("user mobile is" + mobile + ",user id is " + baseUser.getUid().toString() + ",修改密码 change user passWord is" + passWord);
					} catch (Exception e) {
						logger.error("userService.updatePwdByMobile( mobile, passWord)，密码修改失败" + e);
						result.setMsg("密码修改失败");
						result.setRes(0);
					}
					
					result.setMsg("密码修改成功");
					result.setRes(1);
				}else{
					result.setMsg("密码不符合规则，请修改");
					result.setRes(0);
				}
				
			}else{
				result.setMsg("旧密码不正确，请修改");
				result.setRes(0);
			}
				
			}

		return result;
	}
	
	
	
	/** 
	 * @Title: checkPWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param request
	 * @param @param response
	 * @param @param mobile
	 * @param @param passWord
	 * @param @param smsCode
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "校验密码是否一致",  response = BaseApiResult.class, notes = "校验密码是否一致")
	@RequestMapping(value="/checkPWord")
	public BaseApiResult changePWord(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "passWord", value = "密码")@RequestParam(value = "passWord", required = true)String passWord)
       {
		BaseApiResult result = new BaseApiResult();
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();

		String mobile = baseUser.getMobile();
            //判断旧密码是否跟数据库保存密码一致	
			String checkPwd = MD5Util.sha1(passWord);
			boolean passwordRight = StringUtils
					.equals(baseUser.getPassword(), checkPwd);
			if (passwordRight) {
				result.setMsg("密码验证正确");
				result.setRes(1);
				
			}else{
				result.setMsg("输入密码错误");
				result.setRes(0);
			}
				

		return result;
	}
	
	/** 
	 * @Title: updatePWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param @param request
	 * @param @param response
	 * @param @param mobile
	 * @param @param passWord
	 * @param @param smsCode
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "修改密码",  response = BaseApiResult.class, notes = "修改密码")
	@RequestMapping(value="/updatePWord")
	public BaseApiResult updatePWord(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "passWord", value = "密码")@RequestParam(value = "passWord", required = true)String passWord)
       {
		BaseApiResult result = new BaseApiResult();
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();

		String mobile = baseUser.getMobile();
            //判断旧密码是否跟数据库保存密码一致

			if( passWord.trim().matches(regpw)){
				try {
					userService.updatePwdByMobile( mobile, passWord);
					logger.info("user mobile is" + mobile +  "user id is " + baseUser.getUid().toString() + ",修改密码 change user passWord is" + passWord);
				} catch (Exception e) {
					logger.error("userService.updatePwdByMobile( mobile, passWord)，密码修改失败" + e);
					result.setMsg("密码修改失败");
					result.setRes(0);
				}
				result.setMsg("密码修改成功");
				result.setRes(1);
			}else{
				result.setMsg("密码不符合规则，请修改");
				result.setRes(0);
			}
			

		return result;
	}
	
	
	/** 
	 * @Title: updateAppUserInfo 
	 * @Description: TODO(修改用户基本信息) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "修改用户基本信息",  response = BaseApiResult.class, notes = "修改用户基本信息")
	@RequestMapping(value="/updateAppUserInfo")
	public BaseApiResult updateAppUserInfo(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "uname", value = "用户名")String uname, 
			@ApiParam(required = true, name = "uemail", value = "邮箱")String uemail,  
			@ApiParam(required = true, name = "realname", value = "真实姓名")String realname,  
			@ApiParam(required = true, name = "idcard", value = "身份证号码")String idcard,  
			@ApiParam(required = true, name = "info", value = "个人介绍")String info, 
			@ApiParam(required = true, name = "gender", value = "性别")String gender, 
			@ApiParam(required = true, name = "org", value = "用户企业")String org, 
			@ApiParam(required = true, name = "orgId", value = "用户企业")String orgId,
			@ApiParam(required = true, name = "LOCATION", value = "用户所在地区区域区码")String location,
			@ApiParam(required = true, name = "searchType", value = "短信验证码")String smsCode,
			@ApiParam(required = true, name = "industryId", value = "行业类别ID")String industryId,
			@ApiParam(required = true, name = "industry", value = "行业类别名称")String industry,
			@ApiParam(required = true, name = "position", value = "职务")String position,
			@ApiParam(required = true, name = "locationId", value = "地区ID")String locationId){
		BaseApiResult result = new BaseApiResult();
	   BaseUser baseUser = FrontLoginUtil.getCurrentUser();
       User user = new User();
       if(null!=baseUser){
        	user.setUid(baseUser.getUid());
		//用户名进行判断和更新
		if( StringUtils.isNotBlank(uname)){
			boolean checkResult = userRegisterCheckService.checkUserNameExist(uname);
			if (checkResult) {
				user.setUname(uname);
				user.setUid(baseUser.getUid());
				try {
					userService.update(user);
					logger.info("user id is " + baseUser.getUid().toString() + ",用户名进行判断和更新 change user uname is" + uname);
				} catch (Exception e) {
					logger.error("do userService.update(user),用户名进行判断和更新" + e);
				}
				result.setMsg("用户名更改成功");
				result.setRes(1);
				return result;
			}
			result.setMsg("用户名不可用或已注册");
			result.setRes(0);
			return result;
		}
		
		//行业id、行业名称
		if(StringUtils.isNumeric(industryId) && StringUtils.isNotBlank(industry)){
			user.setIndustry(industry);
			user.setIndustryId(Long.valueOf(industryId));
			try {
				userService.update(user);
				result.setRes(1);
				result.setMsg("保存信息成功");
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}
		
		if(StringUtils.isNotBlank(position)|| StringUtils.isNotBlank(locationId)){
			UserInfoVO vo = new UserInfoVO();
			vo.setUserId(baseUser.getUid().toString());
			Map<String,String> map = new HashMap<String, String>();
			if(StringUtils.isNotBlank(locationId)){
				map.put(UserInfoName.LOCATION.name(), locationId);
			}
			
			if(StringUtils.isNotBlank(position)){
				map.put(UserInfoName.POSITION.name(), position);
			}
			vo.setInfoMap(map);
			try {
				userInfoService.batchSave(vo);
				result.setRes(1);
				result.setMsg("保存信息成功");
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}
		
		if(StringUtils.isNotBlank(org)){
				user.setOrg(org);
				try {
					userService.update(user);
					logger.info("user id is " + baseUser.getUid().toString() + ",修改企业名称和id change user org is" + org);
				} catch (Exception e) {
					logger.error("do userService.update(user),uemail验证修改" + e);
				}
				user.setUid(baseUser.getUid());
//				result.setMsg("用户企业/机构更改成功");
				result.setMsg("公司名称更改成功");
				result.setRes(1);
				return result;
		}
		
		if( StringUtils.isNotBlank(orgId)){
			user.setOrgId(Long.valueOf(orgId));
			try {
				userService.update(user);
				logger.info("user id is " + baseUser.getUid().toString() + ",修改企业名称和id change user orgid is " + orgId);
			} catch (Exception e) {
				logger.error("do userService.update(user),uemail验证修改" + e);
			}
			user.setUid(baseUser.getUid());
			result.setMsg("用户企业/机构更改成功");
			result.setRes(1);
			return result;
	  }
		
		
		//uemail验证修改
        if(StringUtils.isNotBlank(uemail)){
        	
			if( uemail.matches(regEmail)){
				boolean checkResult = userRegisterCheckService.checkUserNameExist(uemail);
				if(checkResult){
					int i = 0;
					try {
						user.setUemail(uemail);
						user.setUid(baseUser.getUid());
						try {
							userService.update(user);
							logger.info("user id is " + baseUser.getUid().toString() + ",uemail验证修改 change user uemail is" + uemail);
						} catch (Exception e) {
							i = 1;
							logger.error("do userService.update(user),uemail验证修改" + e);
						}
						if( 1 == i ){
							result.setMsg("邮箱已注册，请重新输入");
							result.setRes(0);
							return result;
						}else{
							result.setMsg("邮箱修改成功");
							result.setRes(1);
							return result;
						}
					
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						result.setMsg("邮箱修改失败");
						result.setRes(0);
						return result;
					}
				}

				
				result.setMsg("邮箱修改失败，邮箱重复");
				result.setRes(0);
				return result;
			}else{
				result.setMsg("邮箱格式不正确");
				result.setRes(0);
			}
        	
        } 
        
        //修改真实姓名realname
        if(StringUtils.isNotBlank(realname)){
			user.setRealname(realname);;
			user.setUid(baseUser.getUid());
			try {
				userService.update(user);
				logger.info("user id is " + baseUser.getUid().toString() + ",修改真实姓名 change user realname is" + realname);
			} catch (Exception e) {
				logger.error("do userService.update(user),修改真实姓名realname" + e);
			}
			result.setMsg("用户真实姓名成功");
			result.setRes(1);
			return result;
        }  
        //修改用户身份证号
        if(StringUtils.isNotBlank(idcard)){
        	
			if( idcard.matches(regIdCard)){
				user.setIdcard(idcard);
				user.setUid(baseUser.getUid());
				try {
					userService.update(user);
					logger.info("user id is " + baseUser.getUid().toString() + ",修改用户身份证号 change user regIdCard is" + idcard);
				} catch (Exception e) {
					logger.error("do userService.update(user),修改用户身份证号" + e);
				}
				result.setMsg("用户身份证号修改成功");
				result.setRes(1);
				return result;
			}else{
				result.setMsg("用户身份证号格式不正确");
				result.setRes(0);
			}
        	
        	
        	
        	

        }  
        
        //修改个人介绍
//		GENDER("性别"),//性别:0-未知(UserAuthName),1-男(UserAuthName),2-女
//		INFO("个人说明"),
//	    LOCATION("所在地"),
//		BIRTHDATE("出生日期"),//出生日期
//		IDCARD_PROVINCE("户籍省份"),//户籍省份
//		IDCARD_CITY("户籍城市"),//户籍城市
        if(StringUtils.isNotBlank(gender)){
        	   Map<String,Object> map =  userInfoService.getOne(user.getUid().toString(), UserInfoName.GENDER);
           
            if(null==map || map.size()<1 || map.isEmpty()){
            	UserInfo userInfo = new UserInfo();
            	userInfo.setUserId(user.getUid().toString());
            	userInfo.setInfoValue(gender);
            	userInfo.setInfoName(UserInfoName.GENDER.name());
            	try {
            		userInfoService.save(userInfo);
            		logger.info("user id is" + user.getUid().toString() + ",change GENDER is"+gender + ",UserInfoName.GENDER.name() is " + UserInfoName.GENDER.name());
				} catch (Exception e) {
					logger.error("do userInfoService.save(userInfo):" + e);
				}
            }else{
            	try {
            		userInfoService.updateOne(user.getUid().toString(), UserInfoName.GENDER,gender);
            		logger.info("user id is " + user.getUid().toString() + ",change user gender is" + gender);
				} catch (Exception e) {
					logger.error("do userInfoService.updateOne(gender):" + e);
				}
            }
        	
			result.setMsg("用户性别修改成功");
			result.setRes(1);
			return result;
        } 
        
        if(StringUtils.isNotBlank(info)){       	
        	try {
        		userInfoService.updateOne(user.getUid().toString(), UserInfoName.INFO,info);
        		logger.info("user id is " + user.getUid().toString() + ",change user info is" + info);
			} catch (Exception e){ 
        		logger.error("do userInfoService.updateOne(info):" + e);
			}
			result.setMsg("用户个人说明修改成功");
			result.setRes(1);
			return result;
        } 
        if(StringUtils.isNotBlank(location)){ 
        	try {
        		userInfoService.updateOne(user.getUid().toString(), UserInfoName.LOCATION,location);
        		logger.info("user id is " + user.getUid().toString() + ",change user location is " + location);
			} catch (Exception e) {
				logger.error("do userInfoService.updateOne(location):" + e);
			}
			result.setMsg("用户地区修改成功");
			result.setRes(1);
			return result;
        } 
        
        
        }else{
			result.setMsg("请先登录客户端");
			result.setRes(0);
        }
        

        return result;
	}
	
	
	
	
/**
 * 根据县市汉字更新用户所在地区
 * @param userInfoVO
 * @return
 */
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "根据县市汉字更新用户所在地区",  response = BaseApiResult.class, notes = "根据县市汉字更新用户所在地区")
	@RequestMapping(value="/updateUserLocation")
	public BaseApiResult updateUserLocation(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "LOCATION", value = "用户所在地区市区汉字")String location){
		BaseApiResult result = new BaseApiResult();
	   BaseUser baseUser = FrontLoginUtil.getCurrentUser();
//	   baseUser = new BaseUser();
//	   baseUser.setUid(1L);
       if(null!=baseUser){ 
    	try {
    	   //根据汉字查询区码
    		CityInfo cityInfo = cityInfoService.findByCityName(location);
    		if(null!=cityInfo && !"".equals(cityInfo)){
    			userInfoService.updateOne(baseUser.getUid().toString(), UserInfoName.LOCATION,cityInfo.getPostcode());
    			result.setMsg("客户所在地修改成功");
    			result.setRes(1);
    			return result;
    		}else{
    			result.setMsg("客户所在地修改失败，未定位当前市区区码");
    			result.setRes(0);
    			return result;
    		}

		} catch (Exception e) {
			logger.error("do userService.updateIOSLocation(LOCATION),LOCATION IOS" + e);
			result.setMsg("客户所在地修改失败，请稍后再试");
			result.setRes(0);
			return result;
		}   
       }else{
			result.setMsg("请先登录客户端");
			result.setRes(0);
       }
       return result;
       }
	
	
	
	@RequestMapping("/info/saveInfo")
	public String saveInfo(UserInfoVO userInfoVO){
		
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();
		
		userInfoVO.getUser().setUid(baseUser.getUid());
		
		userService.update(userInfoVO.getUser());
		
		userInfoVO.setUserId(String.valueOf(baseUser.getUid()));
		
		userInfoService.batchSave(userInfoVO);
		
		return "redirect:/info/viewInfo.html";
	}	
	
	
	/** 
	 * @Title: updateAppUserPhone 
	 * @Description: TODO(更新用户注册号码) 
	 * @param @param request
	 * @param @param response
	 * @return BaseApiResult(返回类型 ) 
	 * @throws 
	 */ 
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "更新用户注册号码",  response = BaseApiResult.class, notes = "更新用户注册号码")
	@RequestMapping(value="/updateAppUserPhone")
	public BaseApiResult updateAppUserInfo(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = true, name = "mobile", value = "手机号")@RequestParam(value = "mobile", required = true)String mobile, 
			@ApiParam(required = true, name = "smsCode", value = "短信验证码")@RequestParam(value = "smsCode", required = true)String smsCode){
		
		BaseApiResult result = new BaseApiResult();
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();

		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				UserCenterResult checkResult = userRegisterService.checkSMSCode(mobile, smsCode, BizTypeEnum.SmsModifyMobile);
				
				if(  checkResult.isSuccess()){
					UserCenterResult userCenterResult = userRegisterCheckService.checkMobileOrEmailExist(mobile, null);
					if( userCenterResult.isSuccess()){
							if( null!=baseUser){
								String oldMobile = baseUser.getMobile();
								User user = userService.findByPhone(oldMobile);
								user.setUomobile(oldMobile);
								user.setUmobile(mobile);
								userService.updateMobile(user);
								baseUser.setMobile(mobile);
								FrontLoginUtil.setCurrentUser(baseUser);
								FrontLoginUtil.refreshUserCache(request,loginCache);
								try {
									sMSCodeService.sendSms( oldMobile,	 "尊敬的用户，您好！您在招融宝绑定的手机号已改为"+mobile+"，如有问题请联系招融宝客服团队400-688-0101");
									sMSCodeService.sendSms( mobile,	 "尊敬的用户，您好！您在招融宝绑定的手机号已改为"+mobile+"，如有问题请联系招融宝客服团队400-688-0101");
								} catch (IOException e) {
									result.setRes(0);
									result.setMsg("用户手机信息修改失败");
								}
								result.setRes(1);
								result.setMsg("用户手机信息修改成功");
							}else{
								result.setRes(0);
								result.setMsg("修改失败，请您先登录");
							}

					}else{
						result.setMsg(userCenterResult.getMsg());
						result.setRes(0);
					}
				}else{
					result.setMsg(checkResult.getMsg());
					result.setRes(0);
				}
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	/**
	 * 
	  * @method: sendModifyMobileAuthCode
	  * @author: ybr
	  * @date: 2015年8月19日
	  * @Description: 修改手机号短信校验码发送接口
	  * @param request
	  * @param response
	  * @param mobile
	  * @return BaseApiResult
	  *
	 */
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@ApiOperation(value = "修改手机号短信校验码发送",  response = BaseApiResult.class, notes = "修改手机号短信校验码发送")
	@RequestMapping(value="/sendModifyMobileAuthCode")
	public BaseApiResult sendModifyMobileAuthCode(HttpServletRequest request,HttpServletResponse response ,
			@ApiParam(required = true, name = "mobile", value = "手机号")
			@RequestParam(value = "mobile", required = true)String mobile){
		BaseApiResult result = new BaseApiResult();
		if( StringUtils.isNotBlank(mobile)){
			if( mobile.matches(regMobile)){
				BizTypeEnum type = BizTypeEnum.SmsModifyMobile;
				int codeType = SendSMSTypeEnum.MODIFY_PHONE.getIndex();
				UserCenterResult sendResult = userRegisterService.sendSMSCode(mobile, type.name(), type, codeType);
				if(sendResult.isSuccess()){
					result.setMsg("短信发送成功");
					return result;
				}
				result.setMsg(sendResult.getMsg());
				result.setRes(0);
			}else{
				result.setMsg("手机号码格式不正确");
				result.setRes(0);
			}
		}else{
			result.setMsg("手机号码不能为空");
			result.setRes(0);
		}
		
		return result;
	}
	
	
	/**
	 * 根据登录用户修改保存用户基本信息
	 * @param request
	 * @param response
	 * @param mobile
	 * @return
	 */
	@RequestMapping(value="/saveUserInfoApi")
	public BaseApiResult saveUserInfoApi(HttpServletRequest request,HttpServletResponse response,
			@ApiParam(required = false, name = "industryId", value = "行业类别ID")@RequestParam(value = "industryId", required = false)String industryId,
			@ApiParam(required = false, name = "industry", value = "行业类别名称")@RequestParam(value = "industry", required = false)String industry,
			@ApiParam(required = false, name = "org", value = "公司名称")@RequestParam(value = "org", required = false)String org,
			@ApiParam(required = false, name = "realname", value = "真实姓名")@RequestParam(value = "realname", required = false)String realname,
			@ApiParam(required = false, name = "position", value = "职务")@RequestParam(value = "position", required = false)String position,
			@ApiParam(required = false, name = "locationId", value = "地区ID")@RequestParam(value = "locationId", required = false)String locationId,
			@ApiParam(required = false, name = "locationName", value = "地区名称(针对iosGPS定位只能定位地区汉字无编码的情况，与locationId互斥)")@RequestParam(value = "locationName", required = false)String locationName,
			@ApiParam(required = false, name = "uemail", value = "uemail")@RequestParam(value = "uemail", required = false)String uemail,
			@ApiParam(required = false, name = "info", value = "个人说明")@RequestParam(value = "info", required = false)String info
			)throws IOException{
		BaseApiResult result= new BaseApiResult();
		result.setMsg("保存客户信息成功");
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();
//		baseUser = new BaseUser();
//		baseUser.setMobile("13638676664");
//		baseUser.setUid(1L);
//		if(StringUtils.isBlank(phone)){
//			result.setRes(0);
//			result.setMsg("保存客户信息失败,用户电话号码不能为空");
//			return result;
//		}
		User user = loginUserService.findByLoginName(baseUser.getMobile());
		if(null!=user){
		if(StringUtils.isNumeric(industryId) || StringUtils.isNotBlank(industry)|| StringUtils.isNotBlank(org) || StringUtils.isNotBlank(realname)|| StringUtils.isNotBlank(uemail)){
			if(StringUtils.isNumeric(industryId) && StringUtils.isNotBlank(industry)){
				user.setIndustry(industry);
				user.setIndustryId(Long.valueOf(industryId));
			}
	        
			if(StringUtils.isNotBlank(org)){
				user.setOrg(org);
			}
			
			if(StringUtils.isNotBlank(realname)){
				user.setRealname(realname);
			}
			if(StringUtils.isNotBlank(uemail)){
				user.setUemail(uemail);;
			}
			
			try {
				userService.update(user);
				result.setRes(1);
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}
		if(StringUtils.isNotBlank(position)|| StringUtils.isNotBlank(locationId) || StringUtils.isNotBlank(info) || StringUtils.isNotBlank(locationName)){
			UserInfoVO vo = new UserInfoVO();
			vo.setUserId(user.getUid().toString());
			Map<String,String> map = new HashMap<String, String>();
			if(StringUtils.isNotBlank(locationId)){
				map.put(UserInfoName.LOCATION.name(), locationId);
			}else if(StringUtils.isNotBlank(locationName)){
				//根据名称查询区域ID
				CityInfo infoCity = cityInfoService.findByCityName(locationName);
				if(null!=infoCity && !"".equals(infoCity)){
					map.put(UserInfoName.LOCATION.name(), infoCity.getPostcode());
				}else{
					result.setRes(0);
					result.setMsg("用户所在地区保存失败，请手动选择");
					return result;
				}
			}
			
			if(StringUtils.isNotBlank(position)){
				map.put(UserInfoName.POSITION.name(), position);
			}
			
			if(StringUtils.isNotBlank(info)){
				map.put(UserInfoName.INFO.name(), info);
			}
			
			
			vo.setInfoMap(map);
			try {
				userInfoService.batchSave(vo);
				result.setRes(1);
				result.setMsg("保存信息成功");
			} catch (Exception e) {
				result.setRes(0);
				result.setMsg("保存客户信息失败");
			}
		}

		}else{
			result.setRes(0);
			result.setMsg("此客户未注册");	
		}
		
		return result;	
	}
}
